package com.hqyj.shop.service.impl;

import com.hqyj.shop.pojo.ProductIndex;
import com.hqyj.shop.mapper.ProductIndexMapper;
import com.hqyj.shop.service.ProductIndexService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hqyj.shop.util.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author rock
 * @since 2024-10-11 09:36:24
 */
@Slf4j
@Service
public class ProductIndexServiceImpl extends ServiceImpl<ProductIndexMapper, ProductIndex> implements ProductIndexService {

    @Resource
    ProductIndexMapper mapper;

    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @Override
    public ResultVo queryIndex() {
        //获取缓存数据，判断键是否存在
        Object obj = redisTemplate.opsForValue().get("index");
        List<ProductIndex> list = null;
        //判断缓存是否有数据
        if(obj==null){
            log.info("从数据库查询数据");
            //查询数据库数据
             list = mapper.selectList(null);
             //为了防止缓存雪崩，设置过期时间是随机数
            Random rd = new Random();
            int num = rd.nextInt(60);
            //存入redis 缓存
            redisTemplate.opsForValue().set("index",list,num, TimeUnit.MINUTES);
        }else{
            log.info("从缓存查询数据");
            //从缓存获取数据
            list = (List<ProductIndex>)obj;
        }
        if( list.size()==0){
            return ResultVo.error("没有查询到数据");
        }

        return ResultVo.success(list);
    }
}
